import router from "./index";
import { RouteLocationNormalized, NavigationGuardNext } from "vue-router";
import { getToken } from "../utils/auth";
import routerx from "../store/modules/route";
import { message } from "ant-design-vue";
import { getRouter, getSider } from "../service/login";
import { addRouter } from "./addRouter";

const whiteList: string[] = ["/login"];

router.beforeEach((to, from, next) => {
  if (getToken()) {
    if (to.path !== "/login") {
      if (routerx.state.init) {
        next();
      } else {
        gotoRouter(to, next);
      }
    } else {
      next("/");
      message.info("你以成功登录");
    }
  } else {
    if (whiteList.indexOf(to.path) !== -1) {
      next();
    } else {
      if (to.path !== "/login") {
        next("/login");
      } else {
        next();
      }
    }
  }
});

const gotoRouter = async (
  to: RouteLocationNormalized,
  next: NavigationGuardNext
) => {
  const data = await getRouter(routerx.state.token);
  console.log(data);
  const asyncRouter = addRouter(data.data.data.router);
  const sider = await getSider(routerx.state.token);
  asyncRouter.forEach((v, index) => {
    router.addRoute(`home${index}`, v);
  });
  routerx.commit("set_init", true);
  routerx.commit("set_sider", sider.data.data.router);
  next({ ...to, replace: true });
};
